Source Code Viewer - Example 3 - EntityUtil

package name.matthewgreet.example3.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * Static methods for converting and creating value objects from entities, and vice versa.
 */
public class EntityUtil {


	/**
     * Transforms a collection of entities into a list of values using the transformer's transform method.
     * @param entities  A collection of any objects for which a transformer has been written
     * @param transformer An entity transformer to transform E into V
     * @return The list of values, will not be null but may be empty. The ordering is not guaranteed
     * @see EntityTransformer#transform(Object)
     */
    public static <E, V> List<V> transform(Collection<E> entities, EntityTransformer<E, V> transformer) {
        transformer.startMultiple(entities);
        try {
            if (entities == null || entities.isEmpty()) return new ArrayList<V>();
            List<V> values = new ArrayList<V>(); 
            for (E e : entities) {
                V record = transformer.transform(e);
                if (record != null) {
                    values.add(record);
                }
            }
            return values; 
        }
        finally {
            transformer.endMultiple(entities);
        }
    }
    
    /**
     * Transforms an entity into a value object using the transformer's transform method.
     * @param entity Any object for which a transformer has been written
     * @param transformer An entity transformer to transform E into V
     * @return A value object which will be null if the entity param is null
     * @see EntityTransformer#transform(Object)
     * @throws IllegalStateException if the transformation fails for any reason.
     */
    public static <E, V> V transform(E entity, EntityTransformer<E, V> transformer) { 
        transformer.startSingle(entity);
        try { 
            if (entity == null) return null; 
            return transformer.transform(entity);
        }
        catch (Exception e) { 
            throw new IllegalStateException("Unable to produce vo for entity due to " + e); 
        }
        finally {
            transformer.endSingle(entity);
        }
    }
}